﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ilanver.Data.NHibernate
{
    public class NHibernateInitializer
    {
        private static readonly object SyncLock = new Object();
        private static NHibernateInitializer _instance;

        protected NHibernateInitializer()
        {

        }

        private bool _nHibernateSessionIsLoaded = false;

        public static NHibernateInitializer Instance()
        {
            if (_instance == null)
            {
                lock (SyncLock)
                {
                    if (_instance == null)
                    {
                        _instance = new NHibernateInitializer();
                    }
                }
            }

            return _instance;
        }

        /// <summary>
        /// This is the method which should be given the call to intialize the NHibernateSession; e.g.,
        /// NHibernateInitializer.Instance().InitializeNHibernateOnce(() => InitializeNHibernateSession());
        /// where InitializeNHibernateSession() is a method which calls NHibernateSession.Init()
        /// </summary>
        /// <param name="initMethod"></param>
        public void InitializeNHibernateOnce(Action initMethod)
        {
            lock (SyncLock)
            {
                if (!_nHibernateSessionIsLoaded)
                {
                    initMethod();
                    _nHibernateSessionIsLoaded = true;
                }
            }
        }
    }
}
